/*
//  Copyright © 2014 Allen County Public Library.

  //        ACPL Mobile is free software: This program is distributed and you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.  ACPL Mobile is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY, including without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with ACPL Mobile. If not, see http://www.gnu.org/licenses/.
 * Author: James Harpe
 * 
 * Description: This class handles web service calls associated with event information.
 * 
 */

package us.in.lib.acpl.Mobile_ACPL.ws;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.StringTokenizer;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.os.AsyncTask;
import android.util.Xml;
import android.view.Gravity;
import android.view.View;
import android.widget.Toast;

import us.in.lib.acpl.Mobile_ACPL.EventListActivity;
import us.in.lib.acpl.Mobile_ACPL.R;
import us.in.lib.acpl.Mobile_ACPL.event.Event;
import us.in.lib.acpl.Mobile_ACPL.util.RestClient;
import us.in.lib.acpl.Mobile_ACPL.util.RestClient.RequestMethod;

public class EventHandler {
    //ACPL: Removed Evanced URL
	public static final String EVENT_URL = "";
	EventListActivity act;
	private int startDate;
	private List<Event> eventList;
	private boolean hasMoreResults = true;

	private String loc = null;
	private String term = null;

	public EventHandler(EventListActivity act) {
		this.act = act;
		startDate = 0;
		eventList = new ArrayList<Event>();
	}

	public void getEvents(String loc, String term) {
		this.loc = loc;
		this.term = term;
		new GetEventsTask().execute(loc, term);
	}

	public void handleEventsResult(List<Event> list) {

		act.setList(list);
	}

	public boolean hasMoreResults() {
		return hasMoreResults;
	}

	public void getMoreResults() {

		new GetEventsTask().execute(loc, term);

	}

	private class GetEventsTask extends AsyncTask<String, Void, List<Event>> {

		@Override
		protected List<Event> doInBackground(String... params) {

			RestClient client = new RestClient(EVENT_URL);

			String lib = null;
			if (params[1] != null) {
				client.AddParam("kw", params[1]);
			}

			List<String> arr = Arrays.asList(act.getResources().getStringArray(
					R.array.libraryLocationsForEventList));
			Integer index = arr.indexOf(params[0]);
			if (index == -1) {
				lib = "all";
			} else {
				lib = index.toString();
			}
			client.AddParam("lib", lib);
			client.AddParam("nd", "14");
			client.AddParam("dm", "exml");
			client.AddParam("do", String.valueOf(startDate));
			startDate += 14;

			try {
				client.Execute(RequestMethod.GET);
			} catch (Exception e) {
				e.printStackTrace();
			}

			String response = client.getResponse();
			ArrayList<Event> list=null; 
			if (response == null) {

				return list;
			}
			list = new ArrayList<Event>();
			Event event = new Event();
			XmlPullParser parser = Xml.newPullParser();

			try {
				parser.setInput(new StringReader(response));

				int eventType = parser.next();

				while (eventType != XmlPullParser.END_DOCUMENT) {
					if (eventType == XmlPullParser.END_TAG) {
						String name = parser.getName();
						if (name.equalsIgnoreCase("item")) {
							list.add(event);
							event = new Event();
						}
					}

					if (eventType == XmlPullParser.START_TAG) {
						String name = parser.getName();
						if (name.equalsIgnoreCase("title")) {
							String text = parser.nextText();
							if (text.equalsIgnoreCase("No Events Currently Scheduled")) {
								break;
							}
							event.setTitle(text);
						}
						if (name.equalsIgnoreCase("date1")) {
							event.setDate(parser.nextText());
						}
						if (name.equalsIgnoreCase("date")) {
							event.setStringDate(parser.nextText());
						}
						if (name.equalsIgnoreCase("time")) {
							event.setTime(parser.nextText());
						}
						if (name.equalsIgnoreCase("length")) {
							event.setLength(parser.nextText());
						}
						if (name.equalsIgnoreCase("description")) {
							event.setDescription(parser.nextText());
						}
						if (name.equalsIgnoreCase("location")) {
							event.setLocation(parser.nextText());
						}
						if (name.equalsIgnoreCase("library")) {
							event.setLibrary(parser.nextText());
						}
						if (name.equalsIgnoreCase("id")) {
							event.setId(parser.nextText());
						}
						if (name.equalsIgnoreCase("eventtypes")) {
							ArrayList<String> types = new ArrayList<String>();
							StringTokenizer tokens = new StringTokenizer(
									parser.nextText(), ",");
							while (tokens.hasMoreTokens()) {
								String item = tokens.nextToken();
								if (item != null
										&& (!item.equalsIgnoreCase(""))
										&& (!item.equalsIgnoreCase(" "))) {
									types.add(item);
								}
							}
							event.setEventTypes(types.toArray(new String[0]));
						}
						if (name.equalsIgnoreCase("agegroups")) {
							
							String ageGroups = parser.nextText();
							event.setAgeGroupString(ageGroups);
							ArrayList<String> types = new ArrayList<String>();
							StringTokenizer tokens = new StringTokenizer(
									ageGroups, ",");
							while (tokens.hasMoreTokens()) {
								String item = tokens.nextToken();
								if (item != null
										&& (!item.equalsIgnoreCase(""))
										&& (!item.equalsIgnoreCase(" "))) {
									types.add(item);
								}
							}

							event.setAgeGroups(types.toArray(new String[0]));
						}

						if (name.equalsIgnoreCase("signup")) {
							event.setSignup(parser.nextText());
						}
						if (name.equalsIgnoreCase("otherinfo")) {
							event.setOtherInfo(parser.nextText());
						}
					}
					eventType = parser.next();
				}
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

			if (list.size() == 0 && startDate>50) {
				hasMoreResults = false;
			}
			return list;
		}

		@Override
		protected void onPostExecute(List<Event> list) {
			
			if(list==null){
				Toast toast = Toast.makeText(act, "Connection error",
						Toast.LENGTH_LONG);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
				act.findViewById(R.id.eventBar).setVisibility(View.GONE);

			}else{
				eventList.addAll(list);
				handleEventsResult(eventList);
			}

		}
	}

	public List<Event> getEventList() {
		return eventList;
	}

}
